package com.hy.springboot.common.filter;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.io.InputStreamSource;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 耗时统计
 * @author lccsetsun
 * @since 2024/2/3 15:17
 **/

@Aspect
@Component
@Slf4j
public class RunTimeAop {

	@Pointcut("execution(* com.hy.*.controller..*(..))")
	public void methodPointCut() {
	}

	@Around("methodPointCut()")
	public Object runTimeStatistics(ProceedingJoinPoint pjp) throws Throwable {
		Signature signature = pjp.getSignature();
		//方法名
		String methodName = signature.getName();
		//参数数组
		Object[] requestParams = pjp.getArgs();
		StringBuffer sb = new StringBuffer();
		for(Object requestParam : requestParams){
			System.out.println(requestParam);
			if (requestParam instanceof HttpServletRequest || requestParam instanceof HttpServletResponse
					|| requestParam instanceof InputStreamSource || pjp.getSignature().getName().equals("file")
			){
				continue;
			}
			if(requestParam!=null){
				sb.append(JSONObject.toJSONString(requestParam));
				sb.append(",");
			}
		}
		String requestParamsString = sb.toString();
		if(requestParamsString.length()>0){
			requestParamsString = requestParamsString.substring(0, requestParamsString.length() - 1);
		}
		//接口应答前打印日志
		log.info(String.format("request msg：%s", requestParamsString));
		//接口调用开始响应起始时间
		Long startDate = System.currentTimeMillis();
		//正常执行方法，即让方法进行执行
		Object response = pjp.proceed();
		Long endDate = System.currentTimeMillis();

		//接口应答之后打印日志
		log.info(String.format("response msg ：%s",JSONObject.toJSONString(response)));
		//接口耗时
		log.info(String.format("methodName: %s total time elapsed ms ：%s", methodName, ((endDate - startDate))));
		return response;
	}

}
